package xyz.mimai.media.netty.chatroom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * https://wiki.jikexueyuan.com/project/netty-4-user-guide/realize-chat.html
 * @ClassName ChatRoomServer
 * @Description TODO
 * @Author 方丈
 * @Date 2021/2/9 10:31
 * @Version 1.0.0
 **/
public class ChatRoomServer {
    public static void main(String[] args) {
        //创建主线程组，只处理连接请求
        EventLoopGroup eventBossGroup = new NioEventLoopGroup(2) ;
        //创建工作线，接收主线程分发过来的任务，完成实际的工作                                                                                                                   程组
        EventLoopGroup eventWorkGroup = new NioEventLoopGroup() ;

        //创建一个服务器端的启动对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //设置服务器的配置
        serverBootstrap.group(eventBossGroup,eventWorkGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("decoder", new StringDecoder());
                        socketChannel.pipeline().addLast("encoder", new StringEncoder());
                        socketChannel.pipeline().addLast(new ServerHandler());
                    }
                });

        System.out.println("聊天室服务端初始化成功，正在启动监听中... ...");

        try {
            ChannelFuture channelFuture = serverBootstrap.bind(7777).sync();
            //添加注册监听，监控关心的事件，当异步处理结束后，会回调监听逻辑
            channelFuture.addListener(
                    (ChannelFutureListener) channelFuture1 -> {
                        if(channelFuture1.isSuccess()){
                            System.out.println("聊天室服务端监听成功监听7777端口... ...");
                        }else{
                            System.out.println("聊天室服务端监听监听7777端口失败... ...");
                        }
                    }
            );
            channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException ine){
            ine.printStackTrace();
        }finally {
            eventBossGroup.shutdownGracefully();
            eventWorkGroup.shutdownGracefully();
        }

    }
}
